<?php

namespace common\models;

use builder\behaviors\DatetimeBehavior;
use Yii;
use yii\db\ActiveQuery;

/**
 * This is the model class for table "{{%tlog}}".
 *
 * @property int $id
 * @property int $aid 管理员ID
 * @property string $route 路由
 * @property string $category 种类
 * @property string $prefix 客户端
 * @property string|null $message 日志信息
 * @property string $created_at
 *
 * @property-read $admin 关联管理员模型
 */
class Tlog extends \builder\base\BaseActiveRecord
{
    /**
     * 重构日期行为配置
     * @return array
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['timestampBehavior'] = [
            'class' => DatetimeBehavior::class,
            'attributes' => [
                self::EVENT_BEFORE_INSERT => ['created_at'],
            ],
        ];

        return $behaviors;
    }

    /**
     * 关联管理员表
     * @return \yii\db\ActiveQuery
     */
    public function getAdmin()
    {
        return $this->hasOne(Admin::class, ['id' => 'aid']);
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%tlog}}';
    }

    /**
     * 获取管理员指定时间段内的操作日志
     * @param string $startDate 开始日期
     * @param string $endDate   结束日期
     * @param null|int $adminID 管理员ID
     * @return array
     */
    public static function getTLogByDateInterval($startDate, $endDate, $adminID = null):array
    {
        return Tlog::activeQuery('id,aid,route,category,message,created_at')
            ->with([
                'admin' => function (ActiveQuery $activeQuery) {
                    return $activeQuery->select('id,username');
                }
            ])
            ->where(['between', 'created_at', $startDate, $endDate])
            ->andFilterWhere(['aid' => $adminID])
            ->orderBy('id DESC')
            ->asArray()
            ->all();
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        $scenarios = parent::scenarios();
        // 新增
        $scenarios['SCE_Tlog_Create'] = ['aid', 'route', 'category', 'prefix', 'message'];

        return $scenarios;
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['aid', 'route', 'category', 'prefix', 'message'], 'required'],
            [['aid'], 'integer'],
            [['message'], 'string'],
            [['created_at'], 'safe'],
            [['route', 'category', 'prefix'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'aid' => '管理员',
            'route' => '路由',
            'category' => '种类',
            'prefix' => '客户端',
            'message' => '日志信息',
            'created_at' => '时间',
        ];
    }
}
